#import <Foundation/Foundation.h>
#import <objc/runtime.h>
#import <QuartzCore/QuartzCore.h>
#import <UIKit/UIKeyboard.h>
#import <LockInfo/Plugin.h>

#import "framework/FWApplication.h"
#import "framework/FWPlugin.h"
#import "framework/FWCommon.h"
#import "framework/FWPreferences.h"

#import "PINewTodo.h"
#import "PIIntegration.h"
#import "PICommon.h"


@implementation PINewTodo


@synthesize navBar, application, text, textLabel, importance, done, hasFired;


// ******************************************************************************************
#pragma mark -
#pragma mark Initialisation and object management

- (id)initWithFrame:(CGRect)rect application:(FWApplication*)appl preferences:(FWPreferences*)prefs
{
    if ((self = [super initWithFrame:rect])) {
        self.application = appl;
        self.hasFired = NO;
        
        NSBundle* bundle = [NSBundle bundleForClass:[self class]];
        
        UIBarButtonItem* doneBtn = [[[UIBarButtonItem alloc]
                                     initWithTitle:localize(bundle, @"Detail/Button/Done")
                                     style:UIBarButtonItemStyleBordered 
                                     target:self
                                     action:@selector(doneClicked)] autorelease];

        doneBtn.enabled = NO;
        
        UIBarButtonItem* cancelBtn = [[[UIBarButtonItem alloc]
                                       initWithTitle:localize(bundle, @"Detail/Button/Cancel")
                                       style:UIBarButtonItemStyleBordered 
                                       target:self
                                       action:@selector(cancelClicked)] autorelease];
        
        const CGFloat toolbarHeight = 44;
        CGRect navBarFrame = CGRectMake(0, 0, rect.size.width, toolbarHeight);
        CGRect windowFrame = CGRectMake(0, toolbarHeight, rect.size.width, rect.size.height - toolbarHeight);
        
        UINavigationBar* nav = [[[UINavigationBar alloc] initWithFrame:navBarFrame] autorelease];
        nav.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        nav.barStyle = UIBarStyleBlackOpaque;
        self.navBar = nav;
        
        UINavigationItem* navItem = [[[UINavigationItem alloc] initWithTitle:localize(bundle, @"New Task/Title")] autorelease];
        navItem.leftBarButtonItem = cancelBtn;
        navItem.rightBarButtonItem = doneBtn;
        
        [nav setItems:[NSArray arrayWithObjects:navItem, nil] animated:NO];
        [self addSubview:nav];
        
        UILabel* label = [[[UILabel alloc] init] autorelease];
        label.backgroundColor = [UIColor clearColor];
        label.textColor = [UIColor darkTextColor];
        label.textColor = [UIColor whiteColor];
        label.font = [UIFont boldSystemFontOfSize:[UIFont labelFontSize]];
        label.text = localize(bundle, @"New Task/Name");
        [label sizeToFit];
        self.textLabel = label;
 
        UITextField* textView = [[[UITextField alloc] initWithFrame:CGRectZero] autorelease];
        textView.delegate = self;
        textView.enablesReturnKeyAutomatically = YES;
        textView.placeholder = localize(bundle, @"New Task/Name Prompt");
        textView.clearButtonMode = UITextFieldViewModeWhileEditing;
        textView.borderStyle = UITextBorderStyleRoundedRect;
        textView.font = [UIFont boldSystemFontOfSize:[UIFont labelFontSize]];
        textView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        self.text = textView;
        
        UISegmentedControl* navControl = [[[UISegmentedControl alloc]
                            initWithItems:
                            [NSArray arrayWithObjects:
                             localize(bundle, @"Importance/None"),
                             localize(bundle, @"Importance/Top"),
                             localize(bundle, @"Importance/High"),
                             localize(bundle, @"Importance/Normal"),
                             localize(bundle, @"Importance/Low"),
                             nil]] autorelease];
        navControl.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        navControl.segmentedControlStyle = UISegmentedControlStyleBar;
        navControl.selectedSegmentIndex = [prefs intValue:kPIOptionsDefaultImportance withDefault:kPIOptionsDefaultImportanceDefault];
        self.importance = navControl;
        
        
        if (FWIsDeviceAnIPad()) {
            label.frame = CGRectMake(windowFrame.origin.x + 80, windowFrame.origin.y + 15, label.frame.size.width, label.frame.size.height);
            textView.frame = CGRectMake(windowFrame.origin.x + 100, label.frame.origin.y + label.frame.size.height + 5, windowFrame.size.width - 180, textView.font.leading + 4);
            
            navControl.frame = CGRectMake(textView.frame.origin.x + 50, textView.frame.origin.y + textView.frame.size.height + 10, textView.frame.size.width - 100, 30);
        }
        else {
            label.frame = CGRectMake(windowFrame.origin.x + 15, windowFrame.origin.y + 15, label.frame.size.width, label.frame.size.height);
            textView.frame = CGRectMake(windowFrame.origin.x + 20, label.frame.origin.y + label.frame.size.height + 5, windowFrame.size.width - 35, textView.font.leading + 4);
            
            navControl.frame = CGRectMake(textView.frame.origin.x, textView.frame.origin.y + textView.frame.size.height + 10, textView.frame.size.width, 30);
        }
        
        [self addSubview:label];
        [self addSubview:textView];
        [self addSubview:navControl];

        self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        self.autoresizesSubviews = YES;
        self.backgroundColor = [UIColor viewFlipsideBackgroundColor];
        self.opaque = YES;
        
        self.done = doneBtn;
    }
    
    return self;
}

- (void)dealloc
{
    [application release];
    [navBar release];
    [text release];
    [textLabel release];
    [done release];
    [importance release];
    
    [super dealloc];
}


// ******************************************************************************************
#pragma mark -
#pragma mark Layout management - try to look reasonable on both iPhone and iPad

- (void)layoutSubviews
{
    CGSize size = FWGetCurrentScreenSize();
    
    CGFloat origin = self.navBar.frame.origin.y + self.navBar.frame.size.height;
    
    CGRect textFrame = self.text.frame;
    CGRect textLabelFrame = self.textLabel.frame;
    CGRect importanceFrame = self.importance.frame;
    
    if (size.height > size.width || FWIsDeviceAnIPad()) {
        textLabelFrame.origin.y = origin + (FWIsDeviceAnIPad() ? 100 : 20);
        textFrame.origin.y = textLabelFrame.origin.y + textLabelFrame.size.height + 10;
        importanceFrame.origin.y = textFrame.origin.y + textFrame.size.height + (FWIsDeviceAnIPad() ? 50 : 20);
    }
    else {
        // Not much room on a hiorizonal iPhone so squeeze things together!
        textLabelFrame.origin.y = origin;
        textFrame.origin.y = textLabelFrame.origin.y + textLabelFrame.size.height + 2;
        importanceFrame.origin.y = textFrame.origin.y + textFrame.size.height + 4;
    }
    
    self.text.frame = textFrame;
    self.textLabel.frame = textLabelFrame;
    self.importance.frame = importanceFrame;
    
    [super layoutSubviews];
}


// ******************************************************************************************
#pragma mark -
#pragma mark Keyboard management - one big hack on a lockscreen!

- (void)willMoveToWindow:(id)window
{
    if (!window) {
        NSLog(@"LI:PITodo: willMoveToWindow NIL called on PINewTodo");

        if (Class peripheral = objc_getClass("UIPeripheralHost")) {
            NSLog(@"LI:PITodo: Using UIPeripheralHost keyboard"); 
            [[peripheral sharedInstance] orderOutAutomatic];
            [[peripheral sharedInstance] setAutomaticAppearanceEnabled:NO];
        }
        else {
            NSLog(@"LI:PITodo: Using UIKeyboard keyboard"); 
            [[UIKeyboard automaticKeyboard] orderOutWithAnimation:YES];
        }
    }
}

- (void)didMoveToWindow
{
    if (self.window) {
        NSLog(@"LI:PITodo: didMoveToWindow not NIL called on PINewTodo");

        [text becomeFirstResponder];
        
        if (Class peripheral = objc_getClass("UIPeripheralHost")) {
            NSLog(@"LI:PITodo: Using UIPeripheralHost keyboard"); 
            [[peripheral sharedInstance] setAutomaticAppearanceEnabled:YES];
            [[peripheral sharedInstance] orderInAutomatic];
        }
        else {
            NSLog(@"LI:PITodo: Using UIKeyboard keyboard"); 
            [[UIKeyboard automaticKeyboard] orderInWithAnimation:YES];
        }
    }
}


// ******************************************************************************************
#pragma mark -
#pragma mark Command button callbacks

- (void)cancelClicked
{
    self.hasFired = YES;
    [self.application.plugin.plugin dismissPreview];
}

- (void)doneClicked
{
    NSString* todoTitle = text.text;
    
    NSLog(@"LI:PITodo: New todo to be created: %@", todoTitle);
    [self.application.plugin.plugin dismissPreview];

    if (self.hasFired)
        return;
    else
        self.hasFired = YES;
    
    enum PIImportanceType importanceCode = PIImportanceNone;
    switch (self.importance.selectedSegmentIndex) {
        case 0:
            importanceCode = PIImportanceNone;
            break;
        case 1:
            importanceCode = PIImportanceTop;
            break;
        case 2:
            importanceCode = PIImportanceHigh;
            break;
        case 3:
            importanceCode = PIImportanceNormal;
            break;
        case 4:
            importanceCode = PIImportanceLow;
            break;
    }
    
    NSURL* url = [NSURL URLWithString:[PIIntegration newTaskURL:todoTitle importance:importanceCode application:application]];
    [self.application.plugin.plugin launchURL:url];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self doneClicked];
    return NO;
}


// ******************************************************************************************
#pragma mark -
#pragma mark Manage Done button state

- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    self.done.enabled = NO;
    return YES;
}

- (BOOL)keyboardInputShouldDelete:(UITextField*)input
{
    self.done.enabled = input.text.length > 1;
    return YES;
}

- (BOOL)keyboardInput:(UITextView*)input shouldInsertText:(NSString *)newtext isMarkedText:(int)marked
{
    self.done.enabled = (self.text.text.length + newtext.length) > 0;
    return YES;
}

@end
